<template>
  <div class="thexgPlayer-wrap">
    <div :class="palyerClass" class="thexgPlayer">
      <div ref="playerEl" class="thexgPlayer"></div>
    </div>
    <div ref="imgEl" :class="imgClass" class="theImagePlayer">
      <Transition name="h2" appear>
        <div v-if="theImageSHOW">
          <img :src="theImage.src" class="theImagePlayer-img" />
        </div>
      </Transition>
    </div>
  </div>
</template>

<script setup lang="ts">
import localForage from "localforage";
import Player, { Events } from "xgplayer";
import { SimplePlayer } from "xgplayer/es";
import "xgplayer/dist/index.min.css";
import { ref, reactive, onMounted, nextTick, computed } from "vue";

const playerEl = ref();
const imgEl = ref();
const theImageSHOW = ref(true);
const theImage = ref({ src: "" });

const theVolume = computed(() => {
    // 0 -10 音量范围
  const volume = Number(getQueryString("volume") || 0);
  return volume > 10 ? 0 : volume / 10;
});

const getQueryString = (name: string, url?: string) => {
  const reg = new RegExp("[&, ?]" + name + "=([^\\&,\\#]*)", "i");
  const value = reg.exec(url || location.href);
  console.log("getQueryString", location.href);
  console.log("getQueryString", value);
  return value ? value[1] : "";
};
const palyerClass = ref("");
const imgClass = ref("thishidden");

const thePlayer = ref<SimplePlayer>();

const props = defineProps({
  // 播放列表
  playlist: {
    type: Array,
    default: () => [],
  },
});

const config = reactive({
  el: undefined,
  url: "",
  controls: false,
  width: "100%", // 宽度可以是 数字 ，也可以是百分比
  height: "100%",
  autoplay: true,
  loop: false,
  autoplayMuted: false,
  volume: theVolume.value,
  playbackRate: [0.5, 0.75, 1, 1.5, 2], // 倍速
});
console.log("config", config);
const playIndex = ref(0);
const playNext = () => {
  console.log("playNext");
  // 获取播放下标
  const _index = playIndex.value + 1;
  console.log("playNext", _index);
  // 下标加1
  // 获取播放对象
  const playItem: any = getPlayItem(_index);

  if (!playItem) {
    console.log("没有下一集");
    play(getPlayItem(0));
    return;
  } else {
    play(playItem);
  }
};
const getPlayItem = (index: number) => {
  // 获取播放下标
  playIndex.value = index;
  const _index = playIndex.value;
  console.log("getPlayItem list", props.playlist);
  console.log("getPlayItem", _index);
  // 下标加1
  return props.playlist[_index];
  // 获取播放对象
};

const initPlayer = () => {
  const player = new Player(config);
  player.on(Events.AUTOPLAY_PREVENTED, () => {
    console.log("自动播放失败");
    // 写入浏览器缓存 是否支持音量自动播放
    try {
      localForage.setItem("canAutoPlayWithVolume", "false", () => {
        window.location.reload();
      });
      console.log("自动播放失败");
    } catch (err) {
      // This code runs if there were any errors.
      console.log(err);
    }
  });
  player.on(Events.AUTOPLAY_STARTED, () => {
    console.log("autoplay success!!");
    if (config.autoplayMuted === false) {
      console.log("autoplay success!! canAutoPlayWithVolume");
      localStorage.setItem("canAutoPlayWithVolume", "true");
    } else {
      console.log("autoplay success!! not Volume");
    }
  });
  player.on(Events.PLAY, () => {
    console.log("play");
  });
  // 播放完成后  播放下一个素材
  player.on(Events.ENDED, () => {
    console.log("end");
    playNext();
  });

  thePlayer.value = player;
  // 初始化后播放
  play(getPlayItem(0));
};

const play = (item: any) => {
  if (item.type === "video") {
    thePlayer.value?.playNext({
      url: item.url,
    });
  } else {
    // 图片播放
    imgElPlay(item);
  }
};
const imgElPlay = (item: any) => {
  console.log("imgElPlay", item);

  const duration = Number(item.dur) || 5;
  console.log("imgElPlay play", duration);
  imgClass.value = "";
  palyerClass.value = "thishidden";
  theImage.value = {
    src: item.url,
  };
  nextTick(() => {
    theImageSHOW.value = true;
    setTimeout(() => {
      theImageSHOW.value = false;
      imgClass.value = "thishidden";
      palyerClass.value = "";
      theImage.value = {
        src: "",
      };
      nextTick(() => {
        playNext();
      });
    }, duration * 1000);
  });
};
onMounted(() => {
  let canAutoPlayWithVolume = true;
  localForage
    .getItem("canAutoPlayWithVolume")
    .then((value) => {
      console.log("canAutoPlayWithVolume getItem 1", value);
      canAutoPlayWithVolume === (value === null ? true : value === "true");

      if (value) {
        if (value === "false") {
          canAutoPlayWithVolume = false;
        } else if (value === "true") {
          canAutoPlayWithVolume = true;
        }
      }
      console.log("canAutoPlayWithVolume getItem 2", canAutoPlayWithVolume);
    })
    .catch((err) => {
      // This code runs if there were any errors
      console.log(err);
    })
    .finally(() => {
      nextTick(() => {
        const autoplayMuted = !canAutoPlayWithVolume;
        config.el = playerEl.value;
        config.autoplayMuted = autoplayMuted;
        console.log("autoplayMuted", autoplayMuted);

        // 调用播放器初始化
        initPlayer();
      });
    });
});
</script>

<style>
.thexgPlayer-wrap {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  display: block;
  position: static;
}

.thexgPlayer {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.theImagePlayer {
  background-color: transparent;
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  visibility: visible;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap;
  flex-direction: row;
}

.thishidden {
  /* background-color: aquamarine !important; */
  visibility: hidden !important;
}

.theImagePlayer-img {
  width: 100%;
  height: auto;
}

/* 动画 */

/* 1. 关键帧 (动画效果) */
@keyframes axisX {
  from {
    transform: translateX(-100%);
  }

  to {
    transform: translateX(0px);
  }
}

/* 2. 过渡类名 */
/* 开始 */
.h2-enter-active {
  background: skyblue;
  animation: axisX 1s;
}

/* 结束 */
.h2-leave-active {
  background: skyblue;
  animation: axisX 1s reverse;
}

/*  */
.xgplayer-start {
  visibility: hidden !important;
}
</style>
